
let db = require('../utils/DB');//数据库
let to = require('../utils/await-to-js');
let { SUCCESS, ERROR } = require('../utils/result');//结果
let { HOST } = require('../utils/CONSTANT');//常量模块


/*
keyword	string	关键词
page	number	分页页码 默认为1
size	number	每页展示条数 默认为16
how	    string	排序条件 'e'代表按照评论来排，'n'按照商品新旧来排，'p'按照商品价格来排
asc	    number	排序方式，1代表升序，其余代表降序
*/

//根据关键字搜索
function searchModel() {
    return async (req, res) => {
        let { keyword = '', page = 1, size = 16, how = '', asc = 1 } = req.query;//接收客户端传递的参数
        if (!keyword) {   //未传递关键字
            ERROR(res, '请输入搜索关键字', null);
            return;
        }

        let rst = await getGoods({ keyword, page, size, how, asc });//获取搜索到的商品
        if (rst.length > 0) {
            let d1 = await getCount(keyword);//获取商品总数量
            // SUCCESS(res, {
            //     data: rst,           //商品列表
            //     totalCount: d1[0].totalCount     //商品总数量
            // });
            res.send({
                code: 200,
                msg: '成功',
                result: {
                    data: rst,           //商品列表
                    totalCount: d1[0].totalCount     //商品总数量
                }
            });
        } else {
            ERROR(res, '关键字查询失败', rst)
        }

        // let [err, data] = await to(db.query(`SELECT * FROM category_first`, [HOST]));
        // err ? ERROR(res, '一级分类查询失败', err) : SUCCESS(res, data);
    };
}

//根据条件获取数据
function getGoods({ keyword, page, how, size, asc }) {
    let offset = (page - 1) * size;//当前页面应该显示的数据的开头
    let order = "ASC";//升序排列
    if (asc != 1) {
        order = "DESC";//降序
    }

    let orderName = 'evalNum';//默认按照评论排序
    //根据how，确定按照什么字段来排列数据
    if (how == 'p') {
        orderName = "goods_price";
    } else if (how == 'n') {
        orderName = "new_status"
    }

    return db.query(`SELECT a.goods_id,a.goods_name,a.goods_price,CONCAT(?,a.image_url) as image_url,a.new_status,COUNT(b.eval_start) as evalNum FROM goods_list as a
    INNER JOIN goods_eval as b ON a.goods_id=b.goods_id
    WHERE a.goods_name LIKE '%${keyword}%'
    GROUP BY a.goods_id
    ORDER BY ${orderName} ${order}
    LIMIT ${offset},${size}`,[HOST]);
}

//获取搜索的商品的总数量
function getCount(keyword) {
    return db.query(`SELECT COUNT(*) as totalCount FROM goods_list WHERE goods_name LIKE '%${keyword}%'`);
}


module.exports = searchModel;